﻿using System.Collections.Generic;
using System.Threading;
using System;

public class MatchRoom
{
    /// <summary>
    /// 房间号
    /// </summary>
    public int roomid = 0;
    /// <summary>
    /// 房间最大人数
    /// </summary>
    public int maxCount = 2;
    /// <summary>
    /// 玩家列表
    /// </summary>
    public List<uint> playerIds = new List<uint>();
    public List<string> playerUsernames = new List<string>();
    /// <summary>
    /// 房间当前人数
    /// </summary>
    public short currentPlayerCount;
    /// <summary>
    /// 帧同步的对象
    /// </summary>
    public LockStepManager lockStepManager = new LockStepManager();
    /// <summary>
    /// 记录玩家同步到的帧数
    /// </summary>
    public Dictionary<uint, int> playerUnsyncOpt = new Dictionary<uint, int>();
    public void StartLockStep()
    {
        Thread thread = new Thread(lockStepManager.Run);
        thread.Start();
    }

    /// <summary>
    /// 添加玩家
    /// </summary>
    /// <param name="guid">玩家的guid</param>
    /// <returns>是否成功</returns>
    public bool AddPlayer(uint guid)
    {
        Player player = PlayerManager.GetPlayer(guid);
        if (player == null)
        {
            Console.WriteLine("AddPlayer失败,玩家为空");
            return false;
        }
        if (playerIds.Count >= maxCount)
        {
            Console.WriteLine("AddPlayer失败,房间满了");
            return false;
        }
        if (playerIds.Contains(guid))
        {
            Console.WriteLine("AddPlayer失败,玩家已经在房间");
            return false;
        }

        playerIds.Add(guid);
        player.roomId = this.roomid;

        playerUnsyncOpt.Add(guid, 0);

        return true;
    }
    public bool Add(string username)
    {
        Player player = PlayerManager.Get(username);
        if (player == null)
        {
            Console.WriteLine("AddPlayer失败,玩家为空");
            return false;
        }
        if (playerUsernames.Count >= maxCount)
        {
            Console.WriteLine("AddPlayer失败,房间满了");
            return false;
        }
        if (playerUsernames.Contains(username))
        {
            Console.WriteLine("AddPlayer失败,玩家已经在房间");
            return false;
        }

        playerUsernames.Add(username);


        return true;
    }
    /// <summary>
    /// Tcp广播
    /// </summary>
    /// <param name="msg"></param>
    public void TcpBroadcast(MsgBase msg)
    {
        for (int i = 0; i < playerIds.Count; i++)
        {
            PlayerManager.GetPlayer(playerIds[i]).Send(msg);
        }
    }
    /// <summary>
    /// Udp广播
    /// </summary>
    /// <param name="msg"></param>
    public void UdpBroadcast(MsgBase msg)
    {
        for (int i = 0; i < playerIds.Count; i++)
        {
            PlayerManager.GetPlayer(playerIds[i]).SendTo(msg);
        }
    }
}

